﻿using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;

namespace UlsLogViewer.Helpers
{
    public static class SerializationHelper
    {
        public static string Serialize<T>(object objectToSerialize)
        {
            var serializedObject = string.Empty;
            using (var Stream = new MemoryStream())
            {
                var serializer = new DataContractJsonSerializer(typeof(T));
                serializer.WriteObject(Stream, objectToSerialize);
                Stream.Flush();
                Stream.Position = 0;
                using (var Reader = new StreamReader(Stream))
                {
                    serializedObject = Reader.ReadToEnd();
                }
            }
            return serializedObject;
        }

        public static T JsonDeserialize<T>(string jsonString)
        {
            var deserializer = new DataContractJsonSerializer(typeof(T));
            using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(jsonString)))
            {
                var obj = (T) deserializer.ReadObject(ms);
                return obj;
            }
        }
    }
}
